package demo.java8.SumTest;

/**
 * 斐波那契数列
 * Created by Administrator on 2017/5/19.
 */
public class FibonacciTest {


    public static void main(String[] args) {
        Fibonacci1.findFibonacci(22);
        Fibonacci1.findIndex(17712);
        Fibonacci2.findFibonacci(22);
        Fibonacci1.findIndex(17712);
    }

}
class Fibonacci2{
    static long befor=0;
    static long temp =1;
    static long now = 0;
    public static void findFibonacci(int index){
        if(index<=1)
            return;
        for (int i = 1; i < index; i++) {
            addNum();
        }
        System.out.println("第"+index+"位为"+now);
        resetNum();
    }
    public static void findIndex(int num){
        findNum(num,0);
        resetNum();
    }
    private static void findNum(int num,int index){
        if(num<=0)
            return;
        addNum();
        if(num==now){
            System.out.println("当前值是第"+(index+1)+"位！");
        }else if(num<now){
            System.out.println("当前值在第"+index+"与"+(index+1)+"之间！");
        }
        findNum(num,index+1);
    }
    private static void addNum(){
        now = befor+temp;
        befor = temp;
        temp = now;
    }
    private static void resetNum(){
        befor = 0;
        temp = 1;
        now = 0;
    }
}
class Fibonacci1{
    static long[] fbnc = new long[100];
    static{
        long befor=0;
        long now =fbnc[0]=1;
        for (int i = 1; i < fbnc.length; i++) {
            fbnc[i] = befor+now;
            befor=now;
            now=fbnc[i];
        }
    }

    public static void findFibonacci(int index){
        if(index<=1||index>100)
            return;
        System.out.println("第"+index+"位为"+fbnc[index-1]);
    }
    public static void findIndex(int num){
        if(num<=0||num>fbnc[99])
            return;
        for (int i = 0; i < fbnc.length; i++) {
            if(num==fbnc[i]){
                System.out.println("当前值是第"+(i+1)+"位！");
                break;
            }else if(num<fbnc[i]){
                System.out.println("当前值在第"+i+"与"+(i+1)+"之间！");
                break;
            }
        }

    }
}
